package handlers

import (
	json2 "encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"zh/cache"
	"zh/models"
	"zh/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "字段为空",
		})
		return
	}
	redis_login_key := "login_error"
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_login_key).Int()
	if errCount >= 3 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误三次,禁止登录",
		})
		return
	}
	var user models.User
	models.DB.Where("username=?", username).First(&user)
	if user.ID == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_login_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_login_key, 3, time.Hour*2)
			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "密码错误三次,封禁两小时",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登陆成功",
		"data": user,
	})
	return
}

func List(c *gin.Context) {
	var xiao []models.Xiao
	redis_list_error := "list_error_"
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, redis_list_error).Result()
	if cacheJson == "" {
		models.DB.Find(&xiao)
		json, _ := json2.Marshal(xiao)
		cache.Rdb.Set(cache.Ctx, redis_list_error, json, time.Hour*2)
	} else {
		json2.Unmarshal([]byte(cacheJson), &xiao)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": xiao,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var xiao models.Xiao
	models.DB.Where("id=?", id).First(&xiao)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": xiao,
	})
	return
}

func Add(c *gin.Context) {
	name := c.PostForm("name")
	price := c.PostForm("price")
	data := models.Xiao{
		Name:  name,
		Price: price,
	}
	models.DB.Create(&data)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": data,
	})
	return
}
